/**
 * 模拟API服务，用于开发阶段
 */
import {
  shopInfo,
  tableInfo,
  categories,
  dishes,
  orders,
  orderStatus,
  mockApiResponse
} from '@/common/utils/mock.js';

// 模拟延迟
const delay = (ms = 500) => {
  return new Promise(resolve => setTimeout(resolve, ms));
};

// 菜单相关接口
export const mockMenuApi = {
  // 获取菜品分类列表
  getCategoryList: async () => {
    await delay();
    return mockApiResponse(categories);
  },
  
  // 获取菜品列表
  getDishList: async (params) => {
    await delay();
    let result = [...dishes];
    
    // 按分类筛选
    if (params && params.categoryId) {
      result = result.filter(item => item.categoryId === params.categoryId);
    }
    
    // 按关键词搜索
    if (params && params.keyword) {
      const keyword = params.keyword.toLowerCase();
      result = result.filter(item => 
        item.name.toLowerCase().includes(keyword) || 
        item.description.toLowerCase().includes(keyword)
      );
    }
    
    return mockApiResponse(result);
  },
  
  // 获取菜品详情
  getDishDetail: async (id) => {
    await delay();
    const dish = dishes.find(item => item.id === id);
    
    if (!dish) {
      return mockApiResponse(null, 404, '菜品不存在');
    }
    
    return mockApiResponse(dish);
  },
  
  // 搜索菜品
  searchDish: async (keyword) => {
    await delay();
    
    if (!keyword) {
      return mockApiResponse([]);
    }
    
    const key = keyword.toLowerCase();
    const result = dishes.filter(item => 
      item.name.toLowerCase().includes(key) || 
      item.description.toLowerCase().includes(key)
    );
    
    return mockApiResponse(result);
  }
};

// 购物车相关接口
export const mockCartApi = {
  // 获取购物车列表
  getCartList: async () => {
    await delay();
    // 从本地存储获取购物车数据
    try {
      const cartData = uni.getStorageSync('cart');
      if (cartData) {
        const cart = JSON.parse(cartData);
        return mockApiResponse(cart);
      }
    } catch (e) {
      console.error('读取购物车数据失败', e);
    }
    
    return mockApiResponse({ items: [], totalQuantity: 0, totalPrice: 0 });
  },
  
  // 添加到购物车
  addToCart: async (data) => {
    await delay();
    // 这里不做实际处理，由前端购物车模块负责
    return mockApiResponse({ success: true });
  },
  
  // 更新购物车商品数量
  updateCartItem: async (data) => {
    await delay();
    // 这里不做实际处理，由前端购物车模块负责
    return mockApiResponse({ success: true });
  },
  
  // 删除购物车商品
  removeCartItem: async (id) => {
    await delay();
    // 这里不做实际处理，由前端购物车模块负责
    return mockApiResponse({ success: true });
  },
  
  // 清空购物车
  clearCart: async () => {
    await delay();
    // 这里不做实际处理，由前端购物车模块负责
    return mockApiResponse({ success: true });
  }
};

// 订单相关接口
export const mockOrderApi = {
  // 创建订单
  createOrder: async (data) => {
    await delay(1000);
    
    // 生成订单ID
    const now = new Date();
    const year = now.getFullYear();
    const month = String(now.getMonth() + 1).padStart(2, '0');
    const day = String(now.getDate()).padStart(2, '0');
    const random = Math.floor(Math.random() * 1000).toString().padStart(3, '0');
    const orderId = `${year}${month}${day}${random}`;
    
    // 创建新订单
    const newOrder = {
      id: orderId,
      tableId: data.tableId || '101',
      totalAmount: data.totalAmount,
      status: orderStatus.PENDING_PAYMENT,
      createTime: now.toISOString(),
      items: data.items || []
    };
    
    // 保存订单
    const localOrders = [...orders, newOrder];
    
    return mockApiResponse({
      orderId,
      order: newOrder
    });
  },
  
  // 获取订单列表
  getOrderList: async (params) => {
    await delay();
    
    let result = [...orders];
    
    // 按状态筛选
    if (params && params.status) {
      result = result.filter(item => item.status === params.status);
    }
    
    // 按时间倒序排序
    result.sort((a, b) => new Date(b.createTime) - new Date(a.createTime));
    
    return mockApiResponse(result);
  },
  
  // 获取订单详情
  getOrderDetail: async (id) => {
    await delay();
    
    const order = orders.find(item => item.id === id);
    
    if (!order) {
      return mockApiResponse(null, 404, '订单不存在');
    }
    
    return mockApiResponse(order);
  },
  
  // 取消订单
  cancelOrder: async (id) => {
    await delay(1000);
    
    const order = orders.find(item => item.id === id);
    
    if (!order) {
      return mockApiResponse(null, 404, '订单不存在');
    }
    
    if (order.status !== orderStatus.PENDING_PAYMENT) {
      return mockApiResponse(null, 400, '只能取消待支付订单');
    }
    
    order.status = orderStatus.CANCELLED;
    order.cancelTime = new Date().toISOString();
    
    return mockApiResponse({ success: true });
  },
  
  // 支付订单
  payOrder: async (data) => {
    await delay(1500);
    
    const order = orders.find(item => item.id === data.orderId);
    
    if (!order) {
      return mockApiResponse(null, 404, '订单不存在');
    }
    
    if (order.status !== orderStatus.PENDING_PAYMENT) {
      return mockApiResponse(null, 400, '订单状态错误');
    }
    
    order.status = orderStatus.PAID;
    order.payTime = new Date().toISOString();
    
    return mockApiResponse({ success: true });
  }
};

// 支付相关接口
export const mockPayApi = {
  // 获取微信支付参数
  getWxPayParams: async (orderId) => {
    await delay(1000);
    
    const order = orders.find(item => item.id === orderId);
    
    if (!order) {
      return mockApiResponse(null, 404, '订单不存在');
    }
    
    // 模拟支付参数
    return mockApiResponse({
      appId: 'wx1234567890',
      timeStamp: String(Math.floor(Date.now() / 1000)),
      nonceStr: Math.random().toString(36).substr(2),
      package: `prepay_id=wx${Math.random().toString(36).substr(2)}`,
      signType: 'MD5',
      paySign: Math.random().toString(36).substr(2)
    });
  },
  
  // 查询支付状态
  checkPayStatus: async (orderId) => {
    await delay();
    
    const order = orders.find(item => item.id === orderId);
    
    if (!order) {
      return mockApiResponse(null, 404, '订单不存在');
    }
    
    return mockApiResponse({
      isPaid: order.status === orderStatus.PAID || order.status === orderStatus.COMPLETED
    });
  }
};

// 餐桌相关接口
export const mockTableApi = {
  // 扫码获取餐桌信息
  getTableInfo: async (tableId) => {
    await delay();
    
    // 这里简单返回固定的桌位信息
    return mockApiResponse({
      ...tableInfo,
      id: tableId || tableInfo.id,
      shopInfo
    });
  }
};

// 用户相关接口
export const mockUserApi = {
  // 用户登录
  login: async (data) => {
    await delay(1000);
    
    // 模拟用户信息
    const userInfo = {
      id: '1',
      nickname: '测试用户',
      avatar: '/static/avatar.png',
      phone: '13800138000'
    };
    
    // 模拟token
    const token = 'mock_token_' + Math.random().toString(36).substr(2);
    
    return mockApiResponse({
      userInfo,
      token
    });
  },
  
  // 获取用户信息
  getUserInfo: async () => {
    await delay();
    
    // 模拟用户信息
    const userInfo = {
      id: '1',
      nickname: '测试用户',
      avatar: '/static/avatar.png',
      phone: '13800138000'
    };
    
    return mockApiResponse(userInfo);
  }
}; 